import { env, envs } from "@/config/env"
import { decodePwy } from "@/utils/encode"
import { isEmpty } from "@/utils/check"
import { uuid, getUrlParams } from "@/utils/utils"

// 本地缓存的key
const localCacheNames = ["token", "isAgreest", "account", "password"]
const sessionCacheNames = ["urlToken", "indexUrl"]

export default {
  state: {
    launchId: "", // 启动ID
    pwy: "", // pwy参数
    env: "", // 环境
    api: "", // 接口地址
    query: {}, // 页面参数
    token: "", // Token
    urlToken: "", // urlToken
    account: "", // 渠道账号
    password: "", // 渠道密码
    pageColor: "#F4F6F7", // 页面背景色
    themeColor: "#fd7441", // 主题色
    indexUrl: "" // 首页地址
  },
  getters: {
    launchId: (state) => state.launchId,
    pwy: (state) => state.pwy,
    env: (state) => state.env,
    api: (state) => state.api,
    query: (state) => state.query,
    token: (state) => state.token,
    urlToken: (state) => state.urlToken,
    account: (state) => state.account,
    password: (state) => state.password,
    pageColor: (state) => state.pageColor,
    themeColor: (state) => state.themeColor,
    indexUrl: (state) => state.indexUrl
  },
  mutations: {
    // 自动初始化
    INIT(state) {
      // 初始化本地缓存
      localCacheNames.forEach((name) => {
        let data = uni.getStorageSync(name)
        if (data) state[name] = data
      })

      // #ifdef WEB
      sessionCacheNames.forEach((name) => {
        let data = window.sessionStorage.getItem(name)
        if (data) {
          try {
            state[name] = JSON.parse(data)
          } catch (error) {
            state[name] = data
          }
        }
      })
      // #endif

      // 初始化环境
      const _env = uni.getStorageSync("env") || env
      state.env = _env
      state.api = envs[_env].api
      // #ifndef WEB
      state.account = envs[_env].account
      state.password = envs[_env].password
      // #endif
      // #ifdef WEB
      const query = window.sessionStorage.getItem("query")
      const account = window.sessionStorage.getItem("account")
      const password = window.sessionStorage.getItem("password")
      state.account = account || envs[_env].account
      state.password = password || envs[_env].password
      if (query) state.query = JSON.parse(query)
      // #endif
    },
    // 初始化App
    INIT_APP(state, data) {
      state.query = data.query
      // #ifdef WEB
      window.sessionStorage.setItem("query", JSON.stringify(data.query))
      if (!state.indexUrl) {
        window.sessionStorage.setItem("indexUrl", window.location.href.split("?")[0])
      }
      // #endif
      // 解析pwy参数
      if (data.query?.pwy) {
        const str = decodePwy(data.query.pwy)
        const params = getUrlParams(str)
        state.pwy = data.query.pwy
        state.account = params.account || params.acc
        state.password = params.password || params.pad
        // #ifdef WEB
        window.sessionStorage.setItem("pwy", data.query.pwy)
        window.sessionStorage.setItem("account", state.account)
        window.sessionStorage.setItem("password", state.password)
        // #endif
      }
      // 替换token
      if (data.query?.tokenId) {
        // 如果本地有urlToken记录
        if (state.urlToken) {
          // 如果本地的urlToken和链接上的tokenId不一致，则将token替换掉
          if (state.urlToken != data.query.tokenId) {
            state.token = data.query.tokenId
            state.urlToken = data.query.tokenId
            uni.setStorageSync("token", data.query.tokenId)
            // #ifdef WEB
            window.sessionStorage.setItem("urlToken", data.query.tokenId)
            // #endif
          }
        } else {
          state.token = data.query.tokenId
          uni.setStorageSync("token", data.query.tokenId)
          // #ifdef WEB
          window.sessionStorage.setItem("urlToken", data.query.tokenId)
          // #endif
        }
      }

      // 设置启动ID
      state.launchId = uuid()
    },

    // 设置环境
    SET_ENV(state, env) {
      state.env = env
      state.account = envs[env].account
      state.password = envs[env].password
      uni.setStorageSync("env", env)
    },

    // 设置token
    SET_TOKEN(state, data) {
      state.token = data
      if (data) {
        uni.setStorageSync("token", data)
      } else {
        uni.removeStorageSync("token")
      }
    },

    // 设置渠道账户
    SET_ACCOUNT(state, data) {
      state.account = data
      uni.setStorageSync("account", data)
    },

    // 设置渠道密码
    SET_PASSWORD(state, data) {
      state.password = data
      uni.setStorageSync("password", data)
    },

    // 设置页面背景色
    SET_PAGE_COLOR(state, data) {
      state.pageColor = data
    },

    // 设置主题
    SET_THEME_COLOR(state, data) {
      state.themeColor = data
    },

    // 清除App数据
    CLEAR_APP(state) {
      state.login = false
      state.token = ""
      state.userInfo = {}
      // uni.clearStorageSync()
    }
  },
  actions: {
    // 自动初始化
    // eslint-disable-next-line prettier/prettier
    init() {},
    // 初始化App
    initApp({ dispatch, commit, state }, options) {
      return new Promise(async (resolve) => {
        commit("INIT_APP", options)
        if (isEmpty(state.token)) await dispatch("getToken")
        dispatch("initCache")
        dispatch("initWebSdk", options)
        dispatch("initLocation")
        dispatch("getCityList")
        dispatch("getIndexDecoInfo")
        // #ifdef MP-WEIXIN
        dispatch("wxMpSilentLogin")
        // #endif
        dispatch("getUserInfo").catch(() => {})
        dispatch("getChannelInfo")
        dispatch("getMyDecoInfo")
        dispatch("getVipOneDecoInfo")
        dispatch("getVipTwoDecoInfo")
        dispatch("getProblemDecoInfo")

        dispatch("initWebTrack", options)
        dispatch("initWeixinMp", options)
        dispatch("getBaseInfo")
        resolve()
      })
    },

    // 清除App数据
    clearApp({ commit }) {
      commit("CLEAR_APP")
    },
    // 清除Token
    clearToken({ commit }) {
      commit("SET_TOKEN", "")
    },

    // 获取token
    getToken({ commit }) {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await uni.$api.public.getToken({}, { checkToken: false, queue: "sync" })
          commit("SET_TOKEN", res.tokenId)
          resolve(res)
        } catch (error) {
          commit("SET_TOKEN", null)
          reject(error)
        }
      })
    },

    // 错误日志
    errorLog(_, data = {}) {
      return new Promise(async (resolve, reject) => {
        try {
          const res = await uni.$api.public.addSystemErrorLog(data, { handleError: false })
          resolve(res)
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
